Day 21 문자열, 사칙연산, 시뮬레이션, 2차원배열, 수학, 배열
Day21 21단계 2023-11-10
2. 안전지대
- 내 풀이 : 배열에서 요소가 1인 경우 문제에서 주어진 대로 그 위치의 양 옆, 위 아래와 대각선 1칸 포함한 영역은 안전지대가 아니므로 -1로 변경해줬다.
- 이 때 이미 1이 존재하는 위치는 변경하지 않고 넘겼다.
- 전체 칸 개수에서 배열의 요소가 1이거나 -1인 위치를 제외한 결과를 반환했다.
- 이 풀이는 원래 풀이에서 챗gpt로 더 간략하게 수정했다.
class Solution {
public int solution(int[][] board) {
int answer = (board.length * board.length);
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[i].length; j++) {
if (board[i][j] == 1) {
for(int row = i-1; row <= i+1; row++) {
for (int col = j-1; col <= j+1; col++) {
if (row >= 0 && row < board.length && col >= 0 && col < board[i].length)
board[row][col] = (board[row][col] != 1) ? -1 : 1;
}
}
}
}
}
for (int[] i : board) {
for (int j : i) {
if (j == -1 || j == 1)
answer--;
}
}
return answer;
}
}
- 원래 작성했던 풀이
- 위 코드와 동일한 컨셉이지만, 대신 배열 영역 밖을 넘어가는 경우는 ArrayIndexOutOfBoundsException 예외처리를 하려고 try-catch문을 넣었었다.
- 하지만 코드가 지나치게 길어지고 쓸데없는 부분이 많은 것 같아 챗gpt로 간략하게 만들 수 있는지 확인했고, for문과 if문을 사용하면 굳이 예외처리를 할 필요가 없다는 것을 알았다.
class Solution {
public int solution(int[][] board) {
int answer = (board.length * board.length);
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[i].length; j++) {
if (board[i][j] == 1) {
try {
board[i][j + 1] = (board[i][j + 1] != 1) ? -1 : 1;
} catch (ArrayIndexOutOfBoundsException e) {}
try {
board[i][j - 1] = (board[i][j - 1] != 1) ? -1 : 1;
} catch (ArrayIndexOutOfBoundsException e) {}
try {
board[i + 1][j] = (board[i + 1][j] != 1) ? -1 : 1;
} catch (ArrayIndexOutOfBoundsException e) {}
try {
board[i + 1][j + 1] = (board[i + 1][j + 1] != 1) ? -1 : 1;
} catch (ArrayIndexOutOfBoundsException e) {}
try {
board[i + 1][j - 1] = (board[i + 1][j - 1] != 1) ? -1 : 1;
} catch (ArrayIndexOutOfBoundsException e) {}
try {
board[i - 1][j] = (board[i - 1][j] != 1) ? -1 : 1;
board[i - 1][j + 1] = (board[i - 1][j + 1] != 1) ? -1 : 1;
} catch (ArrayIndexOutOfBoundsException e) {}
try {
board[i - 1][j - 1] = (board[i - 1][j - 1] != 1) ? -1 : 1;
} catch (ArrayIndexOutOfBoundsException e) {}
}
}
}
for (int[] i : board) {
for (int j : i) {
if (j == -1 || j == 1)
answer--;
}
}
return answer;
}
}